<?php
/**
 * Created by PhpStorm.
 * User: zerodeng
 * Date: 15-5-12
 * Time: 下午4:09
 */

class pagination {

    private $total;
    private $per_page;
    private $link;
    private $page;
    private $page_offset;
    private static $instance;

    public function __construct(){
        $this->per_page = 40;
    }

    public static function get_instance(){
        if(!isset(self::$instance)){
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function set_total($num){
        $this->total = $num;
    }

    public function set_link($link=''){
        if($link){
            $this->link = $link.'?page=';
        }else{
            $this->link = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?page=';
        }
    }

    public function set_page(){
        if(!empty($_GET['page'])){
            $this->page = $_GET['page'];
        }else{
            $this->page = 1;
        }
    }

    public function set_page_offset(){
        if(isset($this->page)){
            $this->page_offset = ($this->page-1)*$this->per_page;
        }
    }

    public function page_limit($mode=''){
        $this->set_page();
        $this->set_page_offset();
        if($mode == 'str'){
            $limit = $this->page_offset.','.$this->per_page;
            return $limit;
        }
        $limit = array($this->page_offset,$this->per_page);
        return $limit;
    }

    public function show_page($page_num=5){
        if(!isset($this->page)){
            $this->set_page();
        }
        $first_page = 1;
        $last_page = ceil($this->total/$this->per_page);
        if(!isset($this->link)){
            $this->set_link();
        }
        $html = '';
        $html .= '<div id="show_page">总共'.$this->total.'条记录 '.$this->page.'/'.$last_page;
        if($this->page != $first_page){
            $html .= '<a href="http://'.$this->link.$first_page.'">首页</a>&nbsp';
        }
        if($page_num>=$last_page){
            for($i = 1;$i<=$last_page;$i++){
                $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
            }
        }else{
            $page_offset = $this->page+$page_num;
            if($page_offset<$last_page){
                for($i=$this->page;$i<=($this->page+$page_num);$i++){
                    $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
                }
            }else{
                for($i=$this->page;$i<=$last_page;$i++){
                    $html .= '|&nbsp<a href="http://'.$this->link.$i.'">'.$i.'</a>&nbsp';
                }
            }

        }
        if($this->page != $last_page){
            $html .= '<a href="http://'.$this->link.$last_page.'">最后一页</a>&nbsp';
        }
        $html .= '</div>';
        return $html;
    }

}